<template>
  <div>
    <el-button type="primary" @click="addtemplate">
      新增模板
    </el-button>
    <el-table
      :data="tableData"
      :span-method="objectSpanMethod"
      :header-cell-style="{background:'#fafafa'}"
      border
      style="width: 100%; margin-top: 20px">
      <el-table-column
        prop="name"
        label="模板名称">
      </el-table-column>
      <el-table-column
        prop="money"
        label="充值金额">
      </el-table-column>
      <el-table-column
        prop="giveMoney"
        label="赠送金额">
      </el-table-column>
      <el-table-column
        label="显示文本">
        <template slot-scope="props">
          <div>{{props.row.showText?props.row.showText:'-'}}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="活动标签">
        <template slot-scope="props">
          <div>{{props.row.tips?props.row.tips:'-'}}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="优先选项">
        <template slot-scope="props">
          <div>{{props.row.defaultDisplay==1?'默认':'-'}}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作">
        <template slot-scope="props">
          <div v-if="props.row.type != 0">
            <el-button type="primary" size="mini" @click="tmpedit(props.row)">修改</el-button>
            <el-button type="danger" size="mini" @click="tmpdelete(props.row)">删除</el-button>
          </div>
          <div v-if="props.row.type == 0">
            <el-button type="primary" size="mini" @click="previeww(props.row)">预览</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <phonepreview ref="perw" :amountList="amountList"></phonepreview>

    <el-dialog :visible.sync="dialogVisible" width="60%" :close-on-click-modal="false" @close="dialogData = [],temname = '',getlist">
      <div class="header">
        <div>充值类型： IC卡充值</div>
        <div class="iptname">模板名称 <el-input v-model="temname" placeholder="请填写模板名称"></el-input><span style="font-size:12px;color:red;margin:16px 0 0 10px;">(注意: 模板名称不能重复)</span></div>
      </div>

      <el-table
        :data="dialogData"
        border
        height="360"
        style="width: 100%; margin-top: 10px">
        <el-table-column
          label="充值金额*">
          <template slot-scope="props">
            <el-input type="number" v-model="props.row.money" @change="moneyipt(props.row)" placeholder="请填写充值金额"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="赠送金额*">
          <template slot-scope="props">
            <el-input type="number" v-model="props.row.giveMoney" @change="givemoneyipt(props.row)" placeholder="请填写赠送金额"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="显示文本">
          <template slot-scope="props">
            <div>{{props.row.showText?props.row.showText:'-'}}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="活动标签">
          <template slot-scope="props">
            <el-input v-model="props.row.tips" maxlength="6" placeholder="如限时、推荐、限100名"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="优先选项"
          width="100">
          <template slot-scope="props">
            <el-switch :value="props.row.defaultDisplay == 1?true:false" @change="firstoption(props.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="80">
          <template slot-scope="props">
            <el-button type="danger" size="mini" @click="pridelete(props.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="addpreview">
        <el-button type="primary" size="mini" @click="addgear">新增充值档位</el-button>
        <el-button size="mini" @click="preview">预览充值模板</el-button>
      </div>
      <phonepreview ref="per" :amountList="amountList"></phonepreview>
      <div class="btnconfirm" v-if="idAddandmodify == 1">
        <el-button type="primary" size="small" @click="addconserve">确认</el-button>
        <el-button type="danger" size="small" @click="dialogVisible = false">取消</el-button>
      </div>
      <div class="btnconfirm" v-if="idAddandmodify == 2">
        <el-button type="primary" size="small" @click="editconserve">确认</el-button>
        <el-button type="danger" size="small" @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import phonepreview from '../../../components/phone-preview/index.vue'
  export default {
    components:{
      phonepreview
    },
    data(){
      return {
        tableData: [],
        dialogVisible: false,
        idAddandmodify: 0,
        temname: '',  // 模板名称
        temid:'',  // 模板id
        arrlist: [],  // 原始数组
        dialogData: [],

        amountList: [],
      }
    },
    computed:{
      // 获取金额列表数组
      groupNum(){
        return new Set(this.tableData.map(o => o.name));
      }
    },
    mounted(){
      this.getlist()
    },
    methods: {
      // 获取IC卡充值模板
      getlist(){
        this.$http({
          url: this.$http.adornUrl('/v1/merchant/user/pay/template/list'),
          method: 'get',
          params: this.$http.adornParams(
            {
              chargeType: 2
            },
          )
        }).then((res) => {
          console.log(res)
          this.arrlist = res.data.data
          let arr = []
          res.data.data.forEach(e => {
            e.userPayTemplateOptionsVoList.forEach(x => {
              x.name = e.name
              x.type = e.type
              x.enabledFlag = e.enabledFlag
              arr.push(x)
            })
          });
          this.tableData = arr
          // console.log(arr)
        }).catch((err) => {
          
        });
      },
      // 根据名称获取金额数量
      classGroup(name){
        return this.tableData.filter(o => o.name == name).length;
      },
      // 根据模板名称获取该模板第一个金额在全量金额中的偏移位置
      classNameLen(name){
        const tmp = Array.from(this.groupNum);
        const index = tmp.indexOf(name);  // 某模板在全模板中的偏移位置
        let len = 0;
        for (let i = 0;i < index;i++){
          len += this.classGroup(tmp[i]);
        }
        return len;
      },
      objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0 || columnIndex === 6) {
          const len = this.classGroup(row.name);
          const lenName = this.classNameLen(row.name);
          if(rowIndex === lenName){
            return {
              rowspan:len,
              colspan:1
            }
          }else return {   // 某模板非首位学生行
            rowspan: 0,
            colspan: 0
          };
        } else {  // 金额信息展示区
          return {
            rowspan: 1,
            colspan: 1
          };
        }
      },
      // 新增模板
      addtemplate(){
        this.idAddandmodify = 1
        this.dialogVisible = true
        this.dialogData.push({
          id: 1,
          money: '',
          giveMoney: '0',
          showText: '',
          tips: '',
          defaultDisplay: 0,
        })
      },
      // 修改模板
      tmpedit(e){
        this.getlist()
        this.idAddandmodify = 2
        let tmpobj = {}
        this.arrlist.map(i => {
          if(e.name == i.name){
            this.temname = i.name
            this.temid = i.id
            tmpobj = i.userPayTemplateOptionsVoList
          }
        })
        this.dialogData = tmpobj
        this.dialogVisible = true
        console.log(tmpobj)
      },
      // 设置优先选项
      firstoption(e){
        this.dialogData.forEach(i => {
          if(e.id == i.id){
            if(i.defaultDisplay == 0){
              i.defaultDisplay = 1
            }else {
              i.defaultDisplay = 0
            }
          }else {
            i.defaultDisplay = 0
          }
        })
      },
      // 删除模板
      tmpdelete(e){
        console.log(e)
        let id = ''
        this.arrlist.forEach(x => {
          if(e.name == x.name){
            id = x.id
          }
        })
        this.$confirm(`确定进行删除操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
          this.$http({
            url: this.$http.adornUrl('/v1/merchant/user/pay/template/delete'),
            method: 'post',
            params: this.$http.adornParams({
              id: id
            })
          }).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getlist()
              }
            })
          }).catch(err => {
            console.log(err)
          })
        }).catch(()=>{

        })
      },
      // 监听充值金额事件
      moneyipt(e){
        this.dialogData.forEach(i => {
          if(e.id == i.id){
            if(i.money < 0 || i.money == ''){
              this.$message({
                message: '充值金额不能小于0',
                type: 'warning'
              });
              i.money = 0
              i.giveMoney = 0
              i.showText = ''
              return
            }
            if(Number(i.money) < Number(i.giveMoney)){
              this.$message({
                message: '充值金额不能小于赠送金额',
                type: 'warning'
              });
              i.giveMoney = 0
              i.showText = ''
            }
          }
        })
      },
      // 监听赠送金额事件
      givemoneyipt(e){
        console.log(e)
        this.dialogData.forEach(i => {
          if(e.id == i.id){
            if(i.money <= 0){
              this.$message({
                message: '请先输入充值金额',
                type: 'warning'
              });
              i.giveMoney = 0
              i.showText = ''
              return
            }
            if(i.giveMoney > 0){
              console.log(i.giveMoney.substr(0,1))
              if(i.giveMoney.substr(0,1) == '0'){
                i.giveMoney = i.giveMoney.slice(1)
              }
              i.showText = '充' + i.money + '元送' + i.giveMoney + '元'
            }else {
              this.$message({
                message: '赠送金额不能小于0',
                type: 'warning'
              });
              i.giveMoney = 0
              i.showText = ''
            }
            if(Number(i.money) < Number(i.giveMoney)){
              this.$message({
                message: '赠送金额不能大于充值金额',
                type: 'warning'
              });
              i.giveMoney = i.money
              i.showText = '充' + i.money + '元送' + i.giveMoney + '元'
            }
          }
        })
      },
      // 新增档位
      addgear(){
        let ifobj = this.dialogData.slice(-1)[0]
        console.log(ifobj)
        if(ifobj.money <= 0){
          this.$message({
            message: '充值金额不能小于等于0',
            type: 'warning'
          });
          return
        }
        if(ifobj.giveMoney < 0 || ifobj.giveMoney === ''){
          this.$message({
            message: '赠送金额不能小于0',
            type: 'warning'
          });
          return
        }
        if(this.dialogData.length >= 6){
          this.$message({
            message: '最多六种档位',
            type: 'warning'
          });
          return
        }
        this.dialogData.push({
          id: ifobj.id + 1,
          money: '',
          giveMoney: '0',
          showText: '',
          tips: '',
          defaultDisplay: 0,
        })
        console.log(this.dialogData)
      },
      // 档位删除
      pridelete(e){
        console.log(e)
        this.$confirm(`确定进行删除操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
          for(let i = 0; i < this.dialogData.length; i++){
            if(this.dialogData[i].id == e.id){
              this.dialogData.splice(i,1)
            }
          }
        }).catch(()=>{

        })
      },
      // 预览模板
      preview(){
        this.$refs.per.previewdialog = true
        this.amountList = this.dialogData
      },
      // previeww
      previeww(e){
        this.$refs.perw.previewdialog = true
        let tmpobj = {}
        this.arrlist.forEach(i => {
          if(e.name == i.name){
            this.temname = i.name
            this.temid = i.id
            tmpobj = i.userPayTemplateOptionsVoList
          }
        })
        this.amountList = tmpobj
      },
      // 新增确认
      addconserve(){
        if(!this.temname){
          this.$message({
            message: '请填写模板名称',
            type: 'warning'
          });
          return
        }
        let arr = []
        this.dialogData.forEach(e => {
          if(e.money <= 0 || e.giveMoney < 0 || e.giveMoney === ''){
            this.$message({
              message: '请检查输入信息',
              type: 'warning'
            });
            return
          }
          arr.push(e.money)
        })
        var nary = arr.sort();
        for(var i = 0; i < nary.length - 1; i++) {
          if(nary[i] == nary[i + 1]) {
            this.$message({
              message: '充值金额不能重复',
              type: 'warning'
            });
            return
          }
        }
        let data = {}
        data.chargeType = 2
        data.id = 0
        data.name = this.temname
        this.dialogData.forEach(x => {
          delete x.id
        })
        data.userPayTemplateOptionsVoList = this.dialogData
        this.$http({
          url: this.$http.adornUrl('/v1/merchant/user/pay/template/add'),
          method: 'post',
          data: this.$http.adornData(
            data
          )
        }).then(res => {
          console.log(res)
          if(res.data.code != 0){
            return
          }
          this.$message({
            message: '添加成功',
            type: 'success'
          });
          this.dialogVisible = false
          this.dialogData = []
          this.getlist()
        }).catch(err => {
          console.log(err)
        })
      },
      // 修改确认
      editconserve(){
        if(!this.temname){
          this.$message({
            message: '请填写模板名称',
            type: 'warning'
          });
          return
        }
        let arr = []
        this.dialogData.forEach(e => {
          if(e.money <= 0 || e.giveMoney < 0 || e.giveMoney === ''){
            this.$message({
              message: '请检查输入信息',
              type: 'warning'
            });
            return
          }
          arr.push(e.money)
        })
        var nary = arr.sort();
        for(var i = 0; i < nary.length - 1; i++) {
          if(nary[i] == nary[i + 1]) {
            this.$message({
              message: '充值金额不能重复',
              type: 'warning'
            });
            return
          }
        }
        let data = {}
        data.chargeType = 2
        data.id = this.temid
        data.name = this.temname
        this.dialogData.forEach(x => {
          delete x.id
        })
        data.userPayTemplateOptionsVoList = this.dialogData
        this.$http({
          url: this.$http.adornUrl('/v1/merchant/user/pay/template/update'),
          method: 'post',
          data: this.$http.adornData(
            data
          )
        }).then(res => {
          console.log(res)
          if(res.data.code != 0){
            return
          }
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.dialogVisible = false
          this.dialogData = []
          this.getlist()
        }).catch(err => {
          console.log(err)
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .el-table--enable-row-hover .el-table__body tr:hover>td {
    background-color: red !important;
  }
  .header {
    display: flex;
    align-items: center;
    div {
      display: flex;
      font-weight: bold;
    }
    .iptname {
      margin-left: 50px;
      align-items: center;
      .el-input {
        flex: 1;
        margin-left: 10px;
      }
    }
  }
  .addpreview {
    margin-top: 10px;
  }
  .btnconfirm {
    margin-top: 20px;
    button {
      padding: 8px 16px;
    }
  }
</style>
